<template>
  <div>
    <a-modal
      :visible.sync="visible"
      v-bind="$attrs"
      v-on="$listeners"
      :maskClosable="false"
      :footer="null"
      width="616px"
      :title="model.text"
      wrapClassName="tenant-modal-container"
      @cancel="closeModal()"
    >
      <div class="tenant-modal-body" v-loading="formLoading">
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :hideRequiredMark="model.text == '查看' ? true : false"
        >
          <!-- 类型 -->
          <a-form-model-item
            ref="menuTypeValue"
            label="类型"
            prop="menuTypeValue"
          >
            <a-select
              v-model="form.menuTypeValue"
              placeholder="请选择类型"
              :loading="menuTypeLoading"
              :disabled="model.id ? true : false"
              @change="menuTypeChange"
            >
              <a-select-option
                :value="item.dicValue"
                v-for="(item, index) in menuTypeSource"
                :key="index"
              >
                {{ item.dicDesc }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <template v-if="form.menuTypeValue == 1">
            <!-- 目录编码   （编辑页面时此字段不可编辑） -->
            <a-form-model-item ref="menuCode" label="编码" prop="menuCode">
              <a-input
                v-model="form.menuCode"
                placeholder="请输入编码"
                :disabled="model.id ? true : false"
                :maxLength="50"
              />
            </a-form-model-item>
            <!-- 目录名称 -->
            <a-form-model-item ref="menuName" label="名称" prop="menuName">
              <a-input
                v-model="form.menuName"
                placeholder="请输入名称"
                :disabled="model.text == '查看' ? true : false"
                :maxLength="50"
              />
            </a-form-model-item>
            <!-- 排序 -->
            <a-form-model-item
              ref="sort"
              label="排序"
              prop="sort"
              v-if="form.menuTypeValue == 1"
            >
              <a-input
                v-model="form.sort"
                type="number"
                placeholder="请输入排序"
                :disabled="model.text == '查看' ? true : false"
                :maxLength="11"
              />
            </a-form-model-item>
          </template>
          <template v-if="form.menuTypeValue == 2 || form.menuTypeValue == 4">
            <!-- 归属系统 -->
            <a-form-model-item
              ref="includeSystem"
              label="归属系统"
              prop="includeSystem"
            >
              <a-select
                v-model="form.includeSystem"
                placeholder="请选择归属系统"
                @change="systemChange"
                :disabled="model.text == '查看' ? true : false"
              >
                <a-select-option
                  :value="item.systemCode"
                  v-for="(item, index) in includeSystemSource"
                  :key="index"
                >
                  {{ item.systemName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
            <!-- 菜单 -->
            <a-form-model-item ref="menuIdList" label="菜单" prop="menuIdList">
              <div
                class="permision-menu-container"
                :class="noChoosePermissFlag && 'error'"
              >
                <a-empty v-if="treeData.length == 0" />
                <a-tree
                  v-else
                  :disabled="model.text == '查看' ? true : false"
                  v-model="checkedKeys"
                  checkable
                  :expanded-keys="expandedKeys"
                  :auto-expand-parent="autoExpandParent"
                  :selected-keys="selectedKeys"
                  :tree-data="treeData"
                  @expand="onExpand"
                  @check="onCheck"
                  :replaceFields="{
                    title: 'permissionName',
                    key: 'id',
                  }"
                />
              </div>
            </a-form-model-item>
            <!-- 菜单类型 -->
            <a-form-model-item
              ref="isSystemMenu"
              label="菜单类型"
              prop="isSystemMenu"
            >
              <a-select
                v-model="form.isSystemMenu"
                placeholder="请选择菜单类型"
                :disabled="model.text == '查看' ? true : false"
              >
                <a-select-option value="0"> 业务菜单 </a-select-option>
                <a-select-option value="1"> 配置中心</a-select-option>
              </a-select>
            </a-form-model-item>
          </template>

          <!-- pc是否展示 -->
          <a-form-model-item ref="pcShow" label="pc是否展示" prop="pcShow">
            <a-radio-group
              v-model="form.pcShow"
              :disabled="model.text == '查看' ? true : false"
            >
              <a-radio value="0"> 是 </a-radio>
              <a-radio value="1"> 否 </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <!-- app是否展示 -->
          <a-form-model-item ref="appShow" label="app是否展示" prop="appShow">
            <a-radio-group
              v-model="form.appShow"
              :disabled="model.text == '查看' ? true : false"
            >
              <a-radio value="0"> 是 </a-radio>
              <a-radio value="1"> 否 </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item label="app菜单图标">
            <a-input
              v-model.trim="form.appModulPath"
              :placeholder="model.text == '查看' ? '' : '请输入app菜单图标'"
              :disabled="model.text == '查看' ? true : false"
            />
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="form-footer">
        <a-button type="default" @click="closeModal()">取消 </a-button>
        <a-button
          type="primary"
          :loading="loading"
          @click="submitForm()"
          v-if="model.text != '查看'"
        >
          提交
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { notificationTip, addAttributeByKey, getLinkDataByKey } from "@/utils";
import { getDictList } from "@/api/user-center/organizationManage.js";
import {
  getIncludeSystem,
  getTenantPermissionZJDAdd,
  getTenantPermissionDetails,
  getTenantUpdate,
} from "@/api/user-center/tenantManage.js";
import { getMenuManageList } from "@/api/user-center/businessManage.js";
export default {
  name: "addChildrenNodeModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    model: {
      type: Object,
      default: {},
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getMenuTypeList();
          this.getIncludeSystemList();
          if (this.model.id) {
            this.getDetail();
          }
        }
      },
      immediate: true,
    },
  },
  data() {
    return {
      loading: false,
      form: {
        //类型
        menuTypeValue: undefined,
        //目录编码
        menuCode: "",
        //目录名称
        menuName: "",
        //pc是否展示
        pcShow: "0",
        //app是否展示
        appShow: "0",
        //排序
        sort: "0",
        //归属系统
        includeSystem: undefined,
        //菜单
        menuIdList: [],
        //菜单类型
        isSystemMenu: undefined,
        //app菜单图标
        appModulPath: "",
      },
      formLoading: false,
      rules: {
        menuTypeValue: [
          { required: true, message: "请选择类型", trigger: "change" },
        ],
        menuCode: [
          { required: true, message: "请输入目录编码", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_-]+$/,
            message: "只能输入英文字母，数字，下划线，中划线",
          },
        ],
        menuName: [
          { required: true, message: "请输入目录名称", trigger: "blur" },
        ],
        pcShow: [
          { required: true, message: "请选择pc是否展示", trigger: "change" },
        ],
        appShow: [
          { required: true, message: "请选择app是否展示", trigger: "change" },
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
        includeSystem: [
          { required: true, message: "请选择归属系统", trigger: "change" },
        ],
        isSystemMenu: [
          { required: true, message: "请选择菜单类型", trigger: "change" },
        ],
        menuIdList: [
          { required: true, validator: this.checkAge, trigger: "change" },
        ],
      },
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      treeData: [],
      noChoosePermissFlag: false,
      //类型
      menuTypeLoading: false,
      menuTypeSource: [],
      //归属系统
      includeSystemSource: [],
    };
  },
  mounted() {},
  methods: {
    //详情
    getDetail() {
      this.formLoading = true;
      let { id } = this.model;
      getTenantPermissionDetails(id)
        .then((res) => {
          let { data } = res;
          this.form = {
            //目录编码
            menuCode: data?.result?.menuCode || "",
            //目录名称
            menuName: data?.result?.menuName || "",
            //pc是否展示
            pcShow: data?.result?.pcShow.toString() || "",
            //app是否展示
            appShow: data?.result?.appShow.toString() || "",
            //排序
            sort: data?.result?.sort,
            //类型
            menuTypeValue: Number(data?.result?.menuTypeValue),
            //菜单类型
            isSystemMenu: data?.result?.isSystemMenu,
            //app菜单图标
            appModulPath: data?.result?.appModulPath,
          };
        })
        .catch((_) => {})
        .finally((_) => {
          this.formLoading = false;
        });
    },

    //查询菜单类型
    getMenuTypeList() {
      this.menuTypeLoading = true;
      getDictList({ dictKey: "menuType" })
        .then((res) => {
          let { data } = res;
          this.menuTypeSource = data.result || [];
        })
        .catch((_) => {
          this.menuTypeSource = [];
        })
        .finally((_) => {
          this.menuTypeLoading = false;
        });
    },
    //选择类型
    menuTypeChange(e) {
      this.form.menuCode = "";
      this.form.menuName = "";
      this.form.includeSystem = undefined;
      this.form.menuIdList = [];
      this.form.isSystemMenu = undefined;
      this.expandedKeys = [];
      this.checkedKeys = [];
      this.treeData = [];
      this.noChoosePermissFlag = false;
      this.$refs["ruleForm"].clearValidate(["menuCode"]);
      this.$refs["ruleForm"].clearValidate(["menuName"]);
      this.$refs["ruleForm"].clearValidate(["includeSystem"]);
      this.$refs["ruleForm"].clearValidate(["menuIdList"]);
      this.$refs["ruleForm"].clearValidate(["isSystemMenu"]);
    },
    //查询归属系统
    getIncludeSystemList() {
      getIncludeSystem()
        .then((res) => {
          let { data } = res;
          this.includeSystemSource = data.result || [];
        })
        .catch((_) => {
          this.includeSystemSource = [];
        });
    },
    //选择系统
    systemChange() {
      this.expandedKeys = [];
      this.checkedKeys = [];
      this.form.menuIdList = [];
      this.noChoosePermissFlag = false;
      this.getMenuList();
    },
    //查询菜单
    getMenuList() {
      let { includeSystem } = this.form;
      getMenuManageList({
        systemCode: includeSystem,
        permissionName: "",
        permissionTypeValue: "",
      })
        .then((res) => {
          let { data } = res;
          let tree = data?.result || [];
          this.treeData = addAttributeByKey(
            null,
            "scopedSlots",
            { icon: "custom" },
            tree,
            "children"
          );
        })
        .catch((_) => {
          this.treeData = [];
        })
        .finally((_) => {});
    },
    //关闭弹窗
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
    //递归树状数据
    dealWithTree(treeList, newTreeList) {
      treeList.map((item) => {
        let tempData = {
          id: item.id,
        };
        if (item.children && item.children.length > 0) {
          tempData.menuIdList = [];
          this.dealWithTree(item.children, tempData.menuIdList);
        }
        newTreeList.push(tempData);
      });
    },
    //处理提交的菜单
    setDealWithMenu() {
      this.form.menuIdList = [];
      let twoArray = [];
      let dealArray = [];
      this.checkedKeys.forEach((item) => {
        twoArray.push(
          getLinkDataByKey(item, "id", this.treeData, false, "children")
        );
      });
      twoArray.forEach((item) => {
        if (item.length != 0) {
          dealArray.push(item);
        }
      });
      let array = dealArray.reduce(function (a, b) {
        return a.concat(b);
      });
      this.dealWithTree(array, this.form.menuIdList);
    },
    //提交
    submitForm() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.form.menuTypeValue != 1) {
            this.setDealWithMenu();
          }
          let { form } = this;
          let { id, text, parentId } = this.model;
          let { tenantCode } = this.$route.query;

          let formJson = {
            //类型
            menuTypeValue: form.menuTypeValue,
            //目录编码
            menuCode: form.menuCode,
            //目录名称
            menuName: form.menuName,
            //pc是否展示
            pcShow: form.pcShow,
            //app是否展示
            appShow: form.appShow,
            //排序
            sort: form.sort,
            //菜单
            menuIdList: form?.menuIdList || [],
            //菜单类型
            isSystemMenu: form.isSystemMenu ? form.isSystemMenu : "",
            tenantCode,
            parentId,
            //app菜单图标
            appModulPath: form.appModulPath,
          };
          if (id) {
            formJson.id = id;
            getTenantUpdate(formJson)
              .then((res) => {
                notificationTip("success", text + "成功！");
                this.closeModal();
                this.$parent.getTableData();
              })
              .catch((_) => {})
              .finally((_) => {
                this.loading = false;
              });
          } else {
            getTenantPermissionZJDAdd(formJson)
              .then((res) => {
                notificationTip("success", text + "成功！");
                this.closeModal();
                this.$parent.getTableData();
              })
              .catch((_) => {})
              .finally((_) => {
                this.loading = false;
              });
          }
        }
      });
    },

    //自定义权限菜单校验
    checkAge(rule, value, callback) {
      let { checkedKeys } = this;
      if (checkedKeys.length == 0) {
        this.noChoosePermissFlag = true;
        return callback(new Error("请选择权限菜单"));
      } else {
        this.noChoosePermissFlag = false;
        callback();
      }
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      this.noChoosePermissFlag = false;
      this.checkedKeys = checkedKeys;
      this.$refs.menuIdList.onFieldChange();
    },
    //重置表单
    resetForm() {
      this.form = {
        //类型
        menuTypeValue: undefined,
        //目录编码
        menuCode: "",
        //目录名称
        menuName: "",
        //pc是否展示
        pcShow: "0",
        //app是否展示
        appShow: "0",
        //排序
        sort: "0",
        //归属系统
        includeSystem: undefined,
        //菜单
        menuIdList: [],
        //菜单类型
        isSystemMenu: undefined,
        //app菜单图标
        appModulPath: "",
      };
      this.noChoosePermissFlag = false;
      this.$refs.ruleForm.resetFields();
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.tenant-modal-container {
  .ant-modal-body {
    padding: 0;
    .tenant-modal-body {
      padding: 20px 60px 20px 40px;
      max-height: 630px;
      .custom-scrollbar();
      .ant-form-item {
        .flex();
        .ant-form-item-label {
          flex-shrink: 0;
          width: 110px;
        }
        .ant-form-item-control-wrapper {
          flex: 1;
        }
        .permision-menu-container {
          width: 414px;
          height: 278px;
          background: #ffffff;
          border: 1px solid #d4d7d8;
          border-radius: 4px;
          .custom-scrollbar();
          &.error {
            border-color: red;
          }
          .ant-tree {
            li {
              width: 100%;
              .ant-tree-node-content-wrapper {
                width: calc(100% - 60px);
              }
            }
          }
        }
      }
    }
    .form-footer {
      text-align: center;
      padding-bottom: 20px;
      button {
        &:last-child {
          margin-left: 20px;
        }
      }
    }
  }
}
</style>
